package io;

import java.io.*;
import java.sql.SQLOutput;
import java.util.Scanner;


public class IODemo15 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入要搜索的路径:");
        String rootPath = scanner.nextLine();
        System.out.println("请输入要查询的词:");
        String word = scanner.next();

        File rootFile = new File(rootPath);
        if(!rootFile.isDirectory()) {
            System.out.println("输入要搜素的路径不正确!");
            return;
        }

        scanDir(rootFile,word);
    }

    private static void scanDir(File rootFile,String word) {
        File[] files = rootFile.listFiles();
        if(files == null) {
            return;
        }
        for(File f:files) {
            System.out.println("当前遍历到:" + f.getAbsolutePath());
            if(f.isFile()) {
                //再文件中搜素
                seachInFile(f,word);
            }else if(f.isDirectory()) {
                //递归遍历
                scanDir(f,word);
            }else {
                //暂时不需要
            }
        }
    }

    private static void seachInFile(File f,String word) {
        try(InputStream inputStream = new FileInputStream(f)) {
            StringBuilder stringBuilder = new StringBuilder();
            while(true) {
                byte[] buffer = new byte[1024];
                int n = inputStream.read(buffer);
                if(n == -1) {
                    break;
                }
                String s = new String(buffer,0,n);
                stringBuilder.append(s);
            }
            //当文件读取完毕,循环结束后,此时stringBuilder就是包含文件整个内容的字符串了
            if(stringBuilder.indexOf(word) == -1) {
                return;
            }
            //找到了,打印文件路径
            System.out.println("找到了,"+word+" 存在于" + f.getAbsolutePath());
            Thread.sleep(3000);
        }catch (IOException e) {
            throw new RuntimeException(e);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}
